/*
 * DBusqueda.java
 *
 * Created on 4 de septiembre de 2006, 11:47 AM
 */
package ig.formato.gui.app;

import ig.basic.util.IModelo;
import ig.formato.dto.CircularDTO;
import ig.formato.dto.basic.DTO;
import ig.formato.modelo.MPlantilla;
import ig.formato.util.IGFormatoException;
import ig.formato.util.MyTableModel;
import ig.formato.util.OBJETOS;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

/**
 *
 * @author  jsanchez
 */
public class DBusqueda extends javax.swing.JDialog {

    String opcion = "";
    IModelo modelo = null;
    
    String nombreClase = null;
    Collection cc = null;
    /** Creates new form DBusqueda */

    public DBusqueda(java.awt.Frame parent, IModelo modelo, Collection cc) {
        super(parent, true);
        this.modelo = modelo;
        initComponents();
        this.CBClonar.setVisible(false);
        this.cCirculares.setVisible(false);
        this.lCircular.setVisible(false);
        java.awt.Dimension dimensionScreen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Rectangle dimensionPantalla = getBounds();
        setLocation((dimensionScreen.width - dimensionPantalla.width) / 2, (dimensionScreen.height - dimensionPantalla.height) / 2);
        this.TableBuscar.getTableHeader().setReorderingAllowed(false);
        this.cc = cc;
        loadFindAll(cc);
        try {
            this.cCirculares.removeAllItems();
            this.cCirculares.addItem("<Todos>");
            if(modelo instanceof MPlantilla )
            for (Object elem : ((MPlantilla)modelo).getCirculares()) {
                this.cCirculares.addItem(elem);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    //this.CBConexiones.setSelectedIndex(0);
    }
    boolean[] columnasEditable = null;
    String[] nameColumnas = null;

    public String getOpcion() {
        return opcion;
    }
    
    private void loadFindAll(Collection cc) {
        try {
            Object[] _objNull ={};
            //Collection cc = this.modelo.lookup().findAll();
            this.TableBuscar.removeAll();
            int fila=0;
            Object[][] data = null;
            for (Object elem : cc) {
                Method[] metodos = elem.getClass().getDeclaredMethods();
                if (data == null) {
                    StringTokenizer token = new StringTokenizer(elem.getClass().getName(), ".");
                    while (token.hasMoreTokens()) {
                        nombreClase = token.nextToken();
                    }
                    nombreClase = nombreClase.substring(0, nombreClase.length() - 3);
                    int j = 0;
                    for (int i = 0; i < metodos.length; i++) {
                        if (metodos[i].getName().equals("getNombre") /*|| metodos[i].getName().equals("getClonar")*/) {
                            j++;
                        }
                        if (!this.CBClonar.isVisible() && metodos[i].getName().equals("getClonar")) {
                            this.CBClonar.setVisible(true);
                            this.cCirculares.setVisible(true);
                            this.lCircular.setVisible(true);
                        }
                    }
                    data = new Object[cc.size()][j];
                    nameColumnas = new String[j];
                    columnasEditable = new boolean[j];
                }
                //metodos[i].getName().substring(3,metodos[i].getName().length()));
                int j = 0;
                for (int i = 0; i < metodos.length; i++) {
                    if (metodos[i].getName().equals("getNombre") /*|| metodos[i].getName().equals("getClonar")*/) {
                        data[fila][j] = metodos[i].invoke(elem, _objNull);
                        if (data[fila][j] == null) {
                            data[fila][j] = "<NONE>";
                        }
                        nameColumnas[j] = metodos[i].getName().substring(3, metodos[i].getName().length());
                        columnasEditable[j] = metodos[i].getName().equals("getClonar") ? true : false;
                        j++;
                    }
                }
                fila++;
            }
            try {
                this.TableBuscar.setModel(new MyTableModel(data, nameColumnas, columnasEditable));
            } catch (Exception e) {
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TableBuscar = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        BAceptar = new javax.swing.JButton();
        BBuscar = new javax.swing.JButton();
        BSalir = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        CBClonar = new javax.swing.JCheckBox();
        cCirculares = new javax.swing.JComboBox();
        lCircular = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        TableBuscar.setAutoCreateRowSorter(true);
        TableBuscar.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "<NONE>"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TableBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableBuscarMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TableBuscar);

        jToolBar1.setOpaque(false);

        BAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/formato/util/images/aceptar.gif"))); // NOI18N
        BAceptar.setBorder(javax.swing.BorderFactory.createEmptyBorder(7, 7, 7, 7));
        BAceptar.setEnabled(false);
        BAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAceptarActionPerformed(evt);
            }
        });
        jToolBar1.add(BAceptar);

        BBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/formato/util/images/buscar.gif"))); // NOI18N
        BBuscar.setBorder(javax.swing.BorderFactory.createEmptyBorder(7, 7, 7, 7));
        BBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BBuscarActionPerformed(evt);
            }
        });
        jToolBar1.add(BBuscar);

        BSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/formato/util/images/salir.gif"))); // NOI18N
        BSalir.setBorder(javax.swing.BorderFactory.createEmptyBorder(7, 7, 7, 7));
        BSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BSalirActionPerformed(evt);
            }
        });
        jToolBar1.add(BSalir);
        jToolBar1.add(jSeparator1);

        CBClonar.setText(org.openide.util.NbBundle.getMessage(DBusqueda.class, "DBusqueda.CBClonar.text")); // NOI18N
        CBClonar.setToolTipText(org.openide.util.NbBundle.getMessage(DBusqueda.class, "DBusqueda.CBClonar.toolTipText")); // NOI18N
        CBClonar.setFocusable(false);
        CBClonar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        CBClonar.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        CBClonar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(CBClonar);

        cCirculares.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cCircularesActionPerformed(evt);
            }
        });

        lCircular.setText(org.openide.util.NbBundle.getMessage(DBusqueda.class, "DBusqueda.lCircular.text")); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jToolBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lCircular, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(cCirculares, 0, 340, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                .add(12, 12, 12))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jToolBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(cCirculares, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(lCircular))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        this.opcion = OBJETOS.NO_SELECCION;
    }//GEN-LAST:event_formWindowClosing

    private void TableBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableBuscarMouseClicked
        id = null;
        if (TableBuscar.getSelectedRow() >= 0) {
            boolean sip = false;
            if (nameColumnas[0].equals("Nombre")) {
                sip = true;
            }
            Object[] o = new Object[0];
            for (Object dto : cc) {
                Method[] m = dto.getClass().getMethods();
                for (int i = 0; i < m.length; i++) {
                    Method method = m[i];
                    if (method.getName().equals("getNombre")) {
                        try {
                            String nombre = method.invoke(dto, o).toString();
                            int col=sip ? 0 :1;
                            String nombreSeleccion = TableBuscar.getValueAt(TableBuscar.getSelectedRow(), col).toString();
                            if (nombre.equals(nombreSeleccion)) {
                                id = ((DTO) dto).getId();
//                                if (dto instanceof InformeDTO) {
//                                    clonar = ((Boolean) TableBuscar.getValueAt(TableBuscar.getSelectedRow(), TableBuscar.getColumnCount() - 1)).booleanValue();
//                                } else {
//                                    clonar = false;
//                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }            
        }
        BAceptar.setEnabled(id!=null?true:false);
        if (evt.getClickCount() >= 2) {
            aceptar();
        }        
    }//GEN-LAST:event_TableBuscarMouseClicked

    private void BSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BSalirActionPerformed
        this.dispose();
        this.opcion = OBJETOS.NO_SELECCION;
    }//GEN-LAST:event_BSalirActionPerformed

    private void BBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BBuscarActionPerformed
        try {
            this.cCirculares.setSelectedIndex(0);
            this.loadFindAll(modelo.buscar());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_BBuscarActionPerformed
    Integer id = null;
    private void BAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAceptarActionPerformed
        aceptar();
    }//GEN-LAST:event_BAceptarActionPerformed

    private void cCircularesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cCircularesActionPerformed
        // TODO add your handling code here:
        if( cCirculares.getItemCount() > 0 && cCirculares.getSelectedItem() !=null && cCirculares.getSelectedItem() instanceof CircularDTO )
        {
            try {
                this.loadFindAll(((MPlantilla) modelo).buscarPorCircular((CircularDTO) cCirculares.getSelectedItem()));
            } catch (IGFormatoException ex) {
                ex.printStackTrace();
            }
        }else if ( cCirculares.getItemCount() > 0 && cCirculares.getSelectedItem() !=null && cCirculares.getSelectedItem() instanceof String ){
            try {
                this.loadFindAll(modelo.buscar());
            } catch (IGFormatoException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_cCircularesActionPerformed
    //private boolean clonar;

    private void aceptar() {
        if (id != null) {
            modelo.setClonar((this.CBClonar.isVisible() && this.CBClonar.isSelected())?true:false);
            modelo.setId(id);
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "Seleccione un objeto de la tabla", "Mensaje", 0);
        }
    }
    //    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new DBusqueda(new javax.swing.JFrame(), true).setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAceptar;
    private javax.swing.JButton BBuscar;
    private javax.swing.JButton BSalir;
    private javax.swing.JCheckBox CBClonar;
    private javax.swing.JTable TableBuscar;
    private javax.swing.JComboBox cCirculares;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lCircular;
    // End of variables declaration//GEN-END:variables

}
